/**
 * 案件管理器
 * 负责管理所有案件、证据、嫌疑人和AI助手的数据
 */
import { 
  DetectiveCase, 
  Evidence, 
  Suspect, 
  AIAssistant,
  createDetectiveCase,
  createEvidence,
  createSuspect,
  createAIAssistant
} from '../entities';
import { JsonStorageService } from './JsonStorageService';

export interface CaseManagerOptions {
  storageKey?: string;
  autoSave?: boolean;
  maxCases?: number;
}

export interface SearchFilters {
  category?: string[];
  difficulty?: string[];
  status?: string[];
  year?: number[];
  tags?: string[];
  location?: string[];
  searchText?: string;
}

export interface CaseStatistics {
  totalCases: number;
  solvedCases: number;
  inProgressCases: number;
  averageScore: number;
  totalTimeSpent: number;
  favoriteCases: number;
  casesByCategory: Record<string, number>;
  casesByDifficulty: Record<string, number>;
  casesByStatus: Record<string, number>;
}

export class CaseManager {
  private storage: JsonStorageService;
  private cases: Map<string, DetectiveCase> = new Map();
  private evidence: Map<string, Evidence> = new Map();
  private suspects: Map<string, Suspect> = new Map();
  private aiAssistant: AIAssistant | null = null;
  private options: CaseManagerOptions;

  constructor(options: CaseManagerOptions = {}) {
    this.options = {
      storageKey: 'ai-detective-cases',
      autoSave: true,
      maxCases: 1000,
      ...options
    };
    
    this.storage = JsonStorageService.getInstance();
    this.loadData();
  }

  /**
   * 加载数据
   */
  private async loadData(): Promise<void> {
    try {
      const data = await this.storage.loadData(this.options.storageKey!);
      
      if (data && typeof data === 'object') {
        // 加载案件
        if (data.cases && Array.isArray(data.cases)) {
          data.cases.forEach((caseData: any) => {
            const caseItem = createDetectiveCase(caseData);
            this.cases.set(caseItem.id, caseItem);
          });
        }
        
        // 加载证据
        if (data.evidence && Array.isArray(data.evidence)) {
          data.evidence.forEach((evidenceData: any) => {
            const evidence = createEvidence(evidenceData);
            this.evidence.set(evidence.id, evidence);
          });
        }
        
        // 加载嫌疑人
        if (data.suspects && Array.isArray(data.suspects)) {
          data.suspects.forEach((suspectData: any) => {
            const suspect = createSuspect(suspectData);
            this.suspects.set(suspect.id, suspect);
          });
        }
        
        // 加载AI助手
        if (data.aiAssistant) {
          this.aiAssistant = createAIAssistant(data.aiAssistant);
        }
      }
      
      // 如果没有AI助手，创建一个默认的
      if (!this.aiAssistant) {
        this.aiAssistant = createAIAssistant();
      }
    } catch (error) {
      console.error('Failed to load data:', error);
      // 创建默认AI助手
      this.aiAssistant = createAIAssistant();
    }
  }

  /**
   * 保存数据
   */
  private async saveData(): Promise<void> {
    if (!this.options.autoSave) return;
    
    try {
      const data = {
        cases: Array.from(this.cases.values()),
        evidence: Array.from(this.evidence.values()),
        suspects: Array.from(this.suspects.values()),
        aiAssistant: this.aiAssistant,
        lastUpdated: new Date().toISOString()
      };
      
      await this.storage.saveData(this.options.storageKey!, data);
    } catch (error) {
      console.error('Failed to save data:', error);
    }
  }

  /**
   * 获取所有案件
   */
  getAllCases(): DetectiveCase[] {
    return Array.from(this.cases.values());
  }

  /**
   * 获取案件
   */
  getCase(caseId: string): DetectiveCase | undefined {
    return this.cases.get(caseId);
  }

  /**
   * 创建案件
   */
  async createCase(caseData: Partial<DetectiveCase> = {}): Promise<DetectiveCase> {
    const newCase = createDetectiveCase(caseData);
    
    // 检查案件数量限制
    if (this.cases.size >= this.options.maxCases!) {
      throw new Error(`Maximum number of cases (${this.options.maxCases}) reached`);
    }
    
    this.cases.set(newCase.id, newCase);
    await this.saveData();
    
    return newCase;
  }

  /**
   * 更新案件
   */
  async updateCase(caseId: string, updates: Partial<DetectiveCase>): Promise<DetectiveCase> {
    const existingCase = this.cases.get(caseId);
    if (!existingCase) {
      throw new Error(`Case with ID ${caseId} not found`);
    }
    
    const updatedCase = {
      ...existingCase,
      ...updates,
      id: caseId, // 确保ID不变
      updatedAt: new Date().toISOString()
    };
    
    this.cases.set(caseId, updatedCase);
    await this.saveData();
    
    return updatedCase;
  }

  /**
   * 删除案件
   */
  async deleteCase(caseId: string): Promise<void> {
    const caseItem = this.cases.get(caseId);
    if (!caseItem) {
      throw new Error(`Case with ID ${caseId} not found`);
    }
    
    // 删除相关证据
    caseItem.evidenceList.forEach(evidenceId => {
      this.evidence.delete(evidenceId);
    });
    
    // 删除相关嫌疑人
    caseItem.suspectList.forEach(suspectId => {
      this.suspects.delete(suspectId);
    });
    
    // 删除案件
    this.cases.delete(caseId);
    await this.saveData();
  }

  /**
   * 搜索案件
   */
  searchCases(filters: SearchFilters = {}): DetectiveCase[] {
    let results = this.getAllCases();
    
    if (filters.searchText) {
      const searchLower = filters.searchText.toLowerCase();
      results = results.filter(caseItem => 
        caseItem.title.toLowerCase().includes(searchLower) ||
        caseItem.description.toLowerCase().includes(searchLower) ||
        caseItem.tags.some(tag => tag.toLowerCase().includes(searchLower)) ||
        caseItem.location.toLowerCase().includes(searchLower)
      );
    }
    
    if (filters.category && filters.category.length > 0) {
      results = results.filter(caseItem => 
        filters.category!.includes(caseItem.category)
      );
    }
    
    if (filters.difficulty && filters.difficulty.length > 0) {
      results = results.filter(caseItem => 
        filters.difficulty!.includes(caseItem.difficulty)
      );
    }
    
    if (filters.status && filters.status.length > 0) {
      results = results.filter(caseItem => 
        filters.status!.includes(caseItem.status)
      );
    }
    
    if (filters.year && filters.year.length > 0) {
      results = results.filter(caseItem => 
        filters.year!.includes(caseItem.year)
      );
    }
    
    if (filters.tags && filters.tags.length > 0) {
      results = results.filter(caseItem => 
        filters.tags!.some(tag => caseItem.tags.includes(tag))
      );
    }
    
    if (filters.location && filters.location.length > 0) {
      results = results.filter(caseItem => 
        filters.location!.includes(caseItem.location)
      );
    }
    
    return results;
  }

  /**
   * 获取案件证据
   */
  getCaseEvidence(caseId: string): Evidence[] {
    const caseItem = this.cases.get(caseId);
    if (!caseItem) {
      return [];
    }
    
    return caseItem.evidenceList
      .map(evidenceId => this.evidence.get(evidenceId))
      .filter(Boolean) as Evidence[];
  }

  /**
   * 获取案件嫌疑人
   */
  getCaseSuspects(caseId: string): Suspect[] {
    const caseItem = this.cases.get(caseId);
    if (!caseItem) {
      return [];
    }
    
    return caseItem.suspectList
      .map(suspectId => this.suspects.get(suspectId))
      .filter(Boolean) as Suspect[];
  }

  /**
   * 添加证据到案件
   */
  async addEvidenceToCase(caseId: string, evidenceData: Partial<Evidence>): Promise<Evidence> {
    const caseItem = this.cases.get(caseId);
    if (!caseItem) {
      throw new Error(`Case with ID ${caseId} not found`);
    }
    
    const evidence = createEvidence({
      ...evidenceData,
      caseId
    });
    
    this.evidence.set(evidence.id, evidence);
    
    // 更新案件的证据列表
    const updatedCase = {
      ...caseItem,
      evidenceList: [...caseItem.evidenceList, evidence.id],
      updatedAt: new Date().toISOString()
    };
    
    this.cases.set(caseId, updatedCase);
    await this.saveData();
    
    return evidence;
  }

  /**
   * 添加嫌疑人到案件
   */
  async addSuspectToCase(caseId: string, suspectData: Partial<Suspect>): Promise<Suspect> {
    const caseItem = this.cases.get(caseId);
    if (!caseItem) {
      throw new Error(`Case with ID ${caseId} not found`);
    }
    
    const suspect = createSuspect({
      ...suspectData,
      caseId
    });
    
    this.suspects.set(suspect.id, suspect);
    
    // 更新案件的嫌疑人列表
    const updatedCase = {
      ...caseItem,
      suspectList: [...caseItem.suspectList, suspect.id],
      updatedAt: new Date().toISOString()
    };
    
    this.cases.set(caseId, updatedCase);
    await this.saveData();
    
    return suspect;
  }

  /**
   * 获取统计数据
   */
  getStatistics(): CaseStatistics {
    const allCases = this.getAllCases();
    
    const stats: CaseStatistics = {
      totalCases: allCases.length,
      solvedCases: allCases.filter(c => c.status === 'solved').length,
      inProgressCases: allCases.filter(c => c.status === 'in_progress').length,
      averageScore: 0,
      totalTimeSpent: allCases.reduce((sum, c) => sum + c.timeSpent, 0),
      favoriteCases: allCases.filter(c => c.isFavorite).length,
      casesByCategory: {},
      casesByDifficulty: {},
      casesByStatus: {}
    };
    
    // 计算平均分
    if (allCases.length > 0) {
      stats.averageScore = allCases.reduce((sum, c) => sum + c.playerScore, 0) / allCases.length;
    }
    
    // 按分类统计
    allCases.forEach(caseItem => {
      stats.casesByCategory[caseItem.category] = (stats.casesByCategory[caseItem.category] || 0) + 1;
      stats.casesByDifficulty[caseItem.difficulty] = (stats.casesByDifficulty[caseItem.difficulty] || 0) + 1;
      stats.casesByStatus[caseItem.status] = (stats.casesByStatus[caseItem.status] || 0) + 1;
    });
    
    return stats;
  }

  /**
   * 获取AI助手
   */
  getAIAssistant(): AIAssistant {
    if (!this.aiAssistant) {
      this.aiAssistant = createAIAssistant();
    }
    return this.aiAssistant;
  }

  /**
   * 更新AI助手
   */
  async updateAIAssistant(updates: Partial<AIAssistant>): Promise<AIAssistant> {
    if (!this.aiAssistant) {
      this.aiAssistant = createAIAssistant();
    }
    
    this.aiAssistant = {
      ...this.aiAssistant,
      ...updates,
      updatedAt: new Date().toISOString()
    };
    
    await this.saveData();
    return this.aiAssistant;
  }

  /**
   * 导出数据
   */
  async exportData(): Promise<string> {
    const data = {
      cases: Array.from(this.cases.values()),
      evidence: Array.from(this.evidence.values()),
      suspects: Array.from(this.suspects.values()),
      aiAssistant: this.aiAssistant,
      exportDate: new Date().toISOString(),
      version: '1.0.0'
    };
    
    return JSON.stringify(data, null, 2);
  }

  /**
   * 导入数据
   */
  async importData(jsonData: string): Promise<void> {
    try {
      const data = JSON.parse(jsonData);
      
      // 清空现有数据
      this.cases.clear();
      this.evidence.clear();
      this.suspects.clear();
      
      // 导入案件
      if (data.cases && Array.isArray(data.cases)) {
        data.cases.forEach((caseData: any) => {
          const caseItem = createDetectiveCase(caseData);
          this.cases.set(caseItem.id, caseItem);
        });
      }
      
      // 导入证据
      if (data.evidence && Array.isArray(data.evidence)) {
        data.evidence.forEach((evidenceData: any) => {
          const evidence = createEvidence(evidenceData);
          this.evidence.set(evidence.id, evidence);
        });
      }
      
      // 导入嫌疑人
      if (data.suspects && Array.isArray(data.suspects)) {
        data.suspects.forEach((suspectData: any) => {
          const suspect = createSuspect(suspectData);
          this.suspects.set(suspect.id, suspect);
        });
      }
      
      // 导入AI助手
      if (data.aiAssistant) {
        this.aiAssistant = createAIAssistant(data.aiAssistant);
      }
      
      await this.saveData();
    } catch (error) {
      throw new Error(`Failed to import data: ${error instanceof Error ? error.message : 'Unknown error'}`);
    }
  }

  /**
   * 清空所有数据
   */
  async clearAllData(): Promise<void> {
    this.cases.clear();
    this.evidence.clear();
    this.suspects.clear();
    this.aiAssistant = createAIAssistant();
    
    await this.saveData();
  }
}